package com.hstc.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Component
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String value = config.getValue();
                if("uuid".equalsIgnoreCase(value)){
                    value = UUID.randomUUID().toString();
                }
                if("jwt".equalsIgnoreCase(value)){
                    value = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYzMjU0MjJ9.XXXXXXX";
                }
                // 创建新的请求并添加头部
                ServerHttpRequest newRequest = exchange.getRequest().mutate()
                        .header(config.getName(), value)
                        .build();
                // 使用修改后的请求继续过滤器链
                ServerWebExchange newExchange = exchange.mutate()
                        .request(newRequest)
                        .build();
                return chain.filter( newExchange);
            }
        };
    }
}
